#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
转码模板API路由
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.database import get_db
from app.models.transcode_template import TranscodeTemplate
from app.schemas.transcode_template import (
    TranscodeTemplateCreate,
    TranscodeTemplateUpdate,
    TranscodeTemplateResponse,
    TranscodeTemplateList
)

router = APIRouter(tags=["转码模板"])

@router.get("/list")
async def get_transcode_templates(
    skip: int = Query(0, ge=0, description="跳过条数"),
    limit: int = Query(100, ge=1, le=1000, description="返回条数"),
    search: Optional[str] = Query(None, description="搜索模板名称"),
    is_active: Optional[bool] = Query(None, description="是否启用"),
    db: Session = Depends(get_db)
):
    """获取转码模板列表 - 统一返回格式"""
    try:
        query = db.query(TranscodeTemplate)
        
        if search:
            query = query.filter(TranscodeTemplate.name.contains(search))
        
        if is_active is not None:
            query = query.filter(TranscodeTemplate.is_active == is_active)
        
        total = query.count()
        templates = query.order_by(TranscodeTemplate.id.desc()).offset(skip).limit(limit).all()
        
        return {
            "code": 200,
            "data": {
                "items": [template.to_dict() for template in templates],
                "total": total
            },
            "message": "success"
        }
        
    except Exception as e:
        return {
            "code": 500,
            "data": {
                "items": [],
                "total": 0
            },
            "message": f"获取模板列表失败: {str(e)}"
        }

@router.get("/{template_id}")
async def get_transcode_template(
    template_id: int,
    db: Session = Depends(get_db)
):
    """获取单个转码模板详情"""
    template = db.query(TranscodeTemplate).filter(
        TranscodeTemplate.id == template_id
    ).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    return {
        "code": 200,
        "message": "success",
        "data": template.to_dict()
    }

@router.post("/")
async def create_transcode_template(
    template: TranscodeTemplateCreate,
    db: Session = Depends(get_db)
):
    """创建转码模板"""
    # 检查名称是否已存在
    existing = db.query(TranscodeTemplate).filter(
        TranscodeTemplate.name == template.name
    ).first()
    
    if existing:
        raise HTTPException(status_code=400, detail="模板名称已存在")
    
    # 如果设置为默认模板，取消其他模板的默认状态
    if template.is_default:
        db.query(TranscodeTemplate).update({"is_default": False})
    
    db_template = TranscodeTemplate(**template.dict())
    db.add(db_template)
    db.commit()
    db.refresh(db_template)
    
    return {
        "code": 200,
        "message": "模板创建成功",
        "data": db_template.to_dict()
    }

@router.put("/{template_id}")
async def update_transcode_template(
    template_id: int,
    template: TranscodeTemplateUpdate,
    db: Session = Depends(get_db)
):
    """更新转码模板"""
    db_template = db.query(TranscodeTemplate).filter(
        TranscodeTemplate.id == template_id
    ).first()
    
    if not db_template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    # 检查名称是否已存在（排除当前模板）
    if template.name:
        existing = db.query(TranscodeTemplate).filter(
            TranscodeTemplate.name == template.name,
            TranscodeTemplate.id != template_id
        ).first()
        
        if existing:
            raise HTTPException(status_code=400, detail="模板名称已存在")
    
    # 如果设置为默认模板，取消其他模板的默认状态
    if template.is_default:
        db.query(TranscodeTemplate).update({"is_default": False})
    
    update_data = template.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_template, field, value)
    
    db.commit()
    db.refresh(db_template)
    
    return {
        "code": 200,
        "message": "模板更新成功",
        "data": db_template.to_dict()
    }

@router.delete("/{template_id}")
async def delete_transcode_template(
    template_id: int,
    db: Session = Depends(get_db)
):
    """删除转码模板"""
    template = db.query(TranscodeTemplate).filter(
        TranscodeTemplate.id == template_id
    ).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    # 不能删除默认模板
    if template.is_default:
        raise HTTPException(status_code=400, detail="不能删除默认模板")
    
    db.delete(template)
    db.commit()
    
    return {"message": "模板删除成功"}

@router.get("/default/")
async def get_default_template(
    db: Session = Depends(get_db)
):
    """获取默认转码模板"""
    template = db.query(TranscodeTemplate).filter(
        TranscodeTemplate.is_default == True
    ).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="默认模板不存在")
    
    return {
        "code": 200,
        "message": "success",
        "data": template.to_dict()
    }

@router.post("/{template_id}/set-default/")
async def set_default_template(
    template_id: int,
    db: Session = Depends(get_db)
):
    """设置默认转码模板"""
    template = db.query(TranscodeTemplate).filter(
        TranscodeTemplate.id == template_id
    ).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    # 取消所有模板的默认状态
    db.query(TranscodeTemplate).update({"is_default": False})
    
    # 设置当前模板为默认
    template.is_default = True
    db.commit()
    
    return {"message": "设置默认模板成功"}